package com.comandadigital.cibus.cardapio;

import android.cardosoesaquetto.comandadigital.adcdcs.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.Toast;

import com.comandadigital.cibus.app.CtrAcessHttp;
import com.comandadigital.cibus.app.CtrFile;

import org.json.JSONObject;

/**
 * Created by everaldo on 27/01/15.
 */
public class TaskCarregaTopCardapio extends AsyncTask<Void, Void, Void> {
    private int codSubGrupo;
    private Boolean acesso=false;
    private ActyCardapio actyCardapio;

    public TaskCarregaTopCardapio(ActyCardapio actyCardapio){
        this.actyCardapio=actyCardapio;
    }

    @Override
    protected Void doInBackground(Void... Void) {
        CtrFile ipServer = new CtrFile(actyCardapio);
        CtrAcessHttp conexao = new CtrAcessHttp();
        JSONObject result1 = conexao.getDataJson("http://"+ipServer.LerArquivo().toString()+"/CCCDWS/TelaCardapio/CarregaTopCardapio");
        if(result1!=null){
            acesso=true;
            Log.i("Teste1 Json: ", result1.toString());
            try{
                JSONObject result2 = result1.getJSONObject("objectTopCardapio");
                codSubGrupo=result2.getInt("codSubGrupo");
            }catch(Exception e){
                Log.i("Log Erro: ",e.getMessage());
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void Void){
        if(acesso==true){
            FrgCardapioGrupos frgGrupos = new FrgCardapioGrupos();

            Bundle argsSubGrupo = new Bundle();
            argsSubGrupo.putInt("position", codSubGrupo);
            FrgCardapioSubGrupos frgSubGrupos = new FrgCardapioSubGrupos();
            frgSubGrupos.setArguments(argsSubGrupo);

            FragmentManager fManager = actyCardapio.getSupportFragmentManager();
            FragmentTransaction fTransaction = fManager.beginTransaction();
            fTransaction.add(R.id.frlGrupos, frgGrupos);
            fTransaction.add(R.id.frlSubGrupo, frgSubGrupos);
            fTransaction.commit();
        }else{
            Toast.makeText(actyCardapio, "Não Foi Possivel Acessar o WebService!\nAguarde alguns segundos e tente novamente", Toast.LENGTH_SHORT).show();
            ((ActyCardapio) actyCardapio).finish();
        }
    }
}
